package org.yaac.server.egql.evaluator;

import static com.google.common.collect.Sets.newHashSet;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;

import org.yaac.server.egql.EntityProperty;
import org.yaac.server.egql.exception.EGQLException;
import org.yaac.server.egql.processor.ProcessData.ProcessDataRecord;
import org.yaac.shared.ErrorCode;



/**
 * @author Max Zhu (thebbsky@gmail.com)
 *
 */
public class SubtractEvaluator extends Evaluator {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private final Evaluator op1;
	
	private final Evaluator op2;
	
	/**
	 * @param op1
	 * @param op2
	 */
	public SubtractEvaluator(Evaluator op1, Evaluator op2) {
		this.op1 = op1;
		this.op2 = op2;
	}

	@Override
	public EvaluationResult evaluate(ProcessDataRecord record) {
		EvaluationResult r1 = op1.evaluate(record);
		EvaluationResult r2 = op2.evaluate(record);

		if (r1.getPayload() instanceof BigDecimal && r2.getPayload() instanceof BigDecimal) {
			BigDecimal bd1 = (BigDecimal) r1.getPayload();
			BigDecimal bd2 = (BigDecimal) r2.getPayload();
			BigDecimal result = bd1.subtract(bd2);
			return new EvaluationResult(result, r1, r2).withTitle(this.getText());
		} else {
			return r1.withWarning(ErrorCode.W002);
		}
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		result = prime * result + ((op1 == null) ? 0 : op1.hashCode());
		result = prime * result + ((op2 == null) ? 0 : op2.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!super.equals(obj))
			return false;
		if (getClass() != obj.getClass())
			return false;
		SubtractEvaluator other = (SubtractEvaluator) obj;
		if (op1 == null) {
			if (other.op1 != null)
				return false;
		} else if (!op1.equals(other.op1))
			return false;
		if (op2 == null) {
			if (other.op2 != null)
				return false;
		} else if (!op2.equals(other.op2))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "SubtractEvaluator [op1=" + op1 + ", op2=" + op2 + "]";
	}

	@Override
	public Set<AggregationEvaluator> aggregationChildren() {
		Set<AggregationEvaluator> result = newHashSet();
		result.addAll(this.op1.aggregationChildren());
		result.addAll(this.op2.aggregationChildren());
		return result;
	}
	
	@Override
	public Set<EntityProperty> nonAggregationProperties() {
		Set<EntityProperty> result = newHashSet();
		result.addAll(this.op1.nonAggregationProperties());
		result.addAll(this.op2.nonAggregationProperties());
		return result;
	}

	@Override
	public void validate() throws EGQLException {		
	}
}
